<template>
  <div class="view-fill">
    <div
      v-if="
        !modifyInfo.visible &&
        !assetApplicationDetailInfo.visible &&
        !contractInfo.visible
      "
      class="app-container-flex"
    >
      <NewFullScreen
        v-model="showDialog"
        title="资产采购单明细"
        :needOperateAffair="true"
        :operateAffairData="affairTableInfo"
        :needReturn="!$route.query.processInstanceId"
        @returnBack="returnBack"
      >
        <template v-slot:full-button>
          <el-button v-if="canUpdate" @click="update">修改</el-button>
          <el-button v-if="canRevoke" @click="handelMethodRequest('revoke')"
            >撤回
          </el-button>
          <el-button
            v-if="canCancelAudit"
            @click="handelMethodRequest('cancelAudit')"
            >销审
          </el-button>
          <el-button v-if="canCheck" @click="handelMethodRequest('check')"
            >批准
          </el-button>
          <!-- <el-button v-if="canBreak" @click="handelMethodRequest('stop')"
            >中止
          </el-button> -->
          <el-button v-if="canSubmit" @click="handelMethodRequest('submit')"
            >提交
          </el-button>
          <el-button v-if="canRefuse" @click="handelMethodRequest('refuse')"
            >拒绝</el-button
          >
          <el-button v-if="canReject" @click="handelMethodRequest('reject')"
            >驳回</el-button
          >
          <el-button v-if="canDoPurch" @click="handelMethodRequest('doPurch')"
            >采购</el-button
          >
          <PopoverPrint
            ref="popoverShow"
            v-model:popoverVisible="popoverVisible"
            :canPrint="canPrint"
            :templateArr="templateArr"
            @tempClick="tempClick"
            @print="print"
          ></PopoverPrint>
          <el-button v-if="canExcel" @click="exportExcel">导出excel</el-button>
        </template>
        <div class="model-panel">
          <div class="model-panel-title">
            <p>{{ $t('basic_information') }}</p>
          </div>
          <div class="model-panel-body">
            <basic-information :info="infoList">
              <template v-slot:basic-contractNo>
                <div class="flex_wrap_start_start">
                  <div
                    class="detail_item_text slip-edit"
                    @click="showContract(infoList.data.contractId)"
                  >
                    {{ infoList.data.contractNo }}
                  </div>
                </div>
              </template>
            </basic-information>
          </div>
        </div>

        <div class="model-panel">
          <div class="model-panel-title">
            <Tooltip :text="$t('detailInfo')"></Tooltip>
          </div>
          <div class="model-panel-body">
            <div class="flex_full_item">
              <!-- 表格 -->
              <page-table
                :refresh="tableInfo.refresh"
                :init-curpage="tableInfo.initCurpage"
                v-model:data="tableInfo.data"
                :api="tableInfo.api"
                :pager="false"
                :summary="true"
                :summary-field-list="tableInfo.summaryFieldList"
                :check-box="false"
                :tab-index="true"
                :query="filterInfo.query"
                :field-list="tableInfo.fieldList"
                :handle="tableInfo.handle"
                :isDynamic="true"
              >
                <template v-slot:col-assetApplicationNo="scope">
                  <span
                    class="slip-edit"
                    @click="showAssetApplicationDetail(scope.row)"
                    >{{ scope.row.assetApplicationNo }}</span
                  >
                </template>
              </page-table>
            </div>
          </div>
        </div>
      </NewFullScreen>
    </div>
    <!-- 资产申论 -->
    <asset-application-details
      v-if="assetApplicationDetailInfo.visible"
      :id="assetApplicationDetailInfo.id"
      v-model:visible="assetApplicationDetailInfo.visible"
      :title="assetApplicationDetailInfo.title"
    />
    <purch-order-modify
      v-if="modifyInfo.visible"
      v-model:visible="modifyInfo.visible"
      :title="modifyInfo.title"
      :tableKey="modifyInfo.tableKey"
      :orderId="modifyInfo.orderId"
      @returnModify="returnModify"
    />
    <contract-detail
      v-if="contractInfo.visible"
      :id="contractInfo.id"
      v-model:visible="contractInfo.visible"
      :title="contractInfo.title"
    />
  </div>
</template>

<!-- <script>
import detailPageViewMixin from '@/mixins/detailPageViewMixin'
export default {
  mixins: [detailPageViewMixin],
}
</script> -->

<script setup name="purchOrderDetailView">
import {
  getAssetPurchOrdersDetailCustomizeListAll,
  getAssetPurchOrderById,
  methodAssetPurchOrder,
  exportAssetPurchOrderDetail,
  printAssetPurchOrderDetail,
} from '@/api/asset.js'
import { orderOpAffairAll } from '@/api/affair'
import { getCustomizeSetting } from '@/api/customize'
import { fatchTemplateByCode } from '@/api/base'
import ContractDetail from '@/views/contractManage/contract/details'
import { doPrint } from '@/utils/exportUtil.js'
import { selectByCodeAndDept } from '@/api/report.js'
import { updatePrintCount } from '@/api/mapping'
import { methodPurchOrder } from '@/api/purch'

const AssetApplicationDetails = defineAsyncComponent(() =>
  import('@/views/asset/assetManage/assetApplication/details')
)
const PurchOrderModify = defineAsyncComponent(() => import('./modify'))

const { proxy } = getCurrentInstance()
const emits = defineEmits()
const props = defineProps(['visible', 'orderId', 'id'])

const tableKey = ref(
  'assetPurchOrderDetail-com.slip.spd.entity.vo.asset.AssetPurchOrderDetailVO'
)
const infoList = ref({
  data: {},
  fieldList: [
    { label: '采购单号', value: 'orderNo', type: 'text' },
    { label: '供应商', value: 'supplierName', type: 'text' },
    { label: '部门', value: 'deptName', type: 'text' },
    { label: '收货联系人', value: 'receiveContacts', type: 'text' },
    { label: '收货电话', value: 'receivePhone', type: 'text' },
    { label: '收货地址', value: 'receiveAddressValue', type: 'text' },
    { label: '状态', value: 'statusValue', type: 'text' },
    { label: '创建人', value: 'createUserName', type: 'text' },
    { label: '创建时间', value: 'createTime', type: 'text' },
    { label: '采购人', value: 'purchUserName', type: 'text' },
    { label: '采购时间', value: 'purchTime', type: 'text' },
    { label: '最后收货时间', value: 'lastReceiveTime', type: 'text' },
    { label: '最后入库时间', value: 'lastStoreTime', type: 'text' },
    { label: '合同', value: 'contractNo', type: 'slot' },
    { label: '审批人', value: 'checkUserName', type: 'text' },
    { label: '审批意见', value: 'checkOpt', type: 'text' },
    { label: '备注', value: 'remark', type: 'text' },
  ],
})
// 过滤相关配置
const filterInfo = ref({
  sortArr: [],
  copyQueryMap: {},
  query: {
    queryMap: {
      orderId: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: null,
      },
    },
    queryParams: {},
    sortString: '',
    copyQueryMap: {},
    groupMap: {},
    groups: [],
    customizeUserVO: {},
  },
  searchList: [],
  searchBtn: [],
  btnList: [],
})
// 表格相关
const tableInfo = ref({
  api: undefined,
  summaryFieldList: [
    { value: 'qty', formatter: proxy.$fn.qtyFormatter },
    { value: 'sumAmount', formatter: proxy.$fn.TripartiteMethod },
  ],
  fieldList: [],
  refresh: 1,
  initCurpage: 1,
  data: [],
  selections: [],
})
const affairTableInfo = ref({
  api: orderOpAffairAll,
  query: {
    orderType: 0,
    orderId: props.orderId || props.id,
    sort: 'operate_time desc',
  },
})
const modifyInfo = ref({
  visible: false,
  title: '',
  orderId: '',
  tableKey: '',
})
const assetApplicationDetailInfo = ref({
  id: '',
  visible: false,
  title: '资产申论详情',
})
const contractInfo = ref({
  id: '',
  visible: false,
  title: '合同详情',
})
const systemConfig = ref('')

const canPrint = computed(() => {
  return (
    proxy.$permission('assetPurchOrder:printDetail') &&
    infoList.value.data.status !== 1
  )
})
const canExcel = computed(() => {
  return (
    proxy.$permission('assetPurchOrder:excel') &&
    infoList.value.data.status !== 1
  )
})
//驳回
const canReject = computed(() => {
  return (
    proxy.$permission('assetPurchOrder:reject') &&
    infoList.value.data.status === 2 &&
    proxy.$store.state.permission.systemConfig
      .allow_asset_purch_order_approval == 1
  )
})
//拒绝
const canRefuse = computed(() => {
  return (
    proxy.$permission('assetPurchOrder:refuse') &&
    infoList.value.data.status === 2 &&
    proxy.$store.state.permission.systemConfig
      .allow_asset_purch_order_approval == 1
  )
})
const canDoPurch = computed(() => {
  return (
    proxy.$permission('assetPurchOrder:doPurch') &&
    infoList.value.data.status === 3
  )
})
const canSubmit = computed(() => {
  return (
    proxy.$permission('assetPurchOrder:submit') &&
    (infoList.value.data.status === 1 || infoList.value.data.status === 5)
  )
})
const canCheck = computed(() => {
  return (
    proxy.$permission('assetPurchOrder:check') &&
    infoList.value.data.status === 2 &&
    proxy.$store.state.permission.systemConfig
      .allow_asset_purch_order_approval == 1
  )
})
const canRevoke = computed(() => {
  return (
    proxy.$permission('assetPurchOrder:revoke') &&
    (infoList.value.data.status === 2 ||
      (infoList.value.data.status === 3 &&
        proxy.$store.state.permission.systemConfig
          .allow_asset_purch_order_approval == 0))
  )
})
const canUpdate = computed(() => {
  return (
    proxy.$permission('assetPurchOrder:update') &&
    (infoList.value.data.status === 1 || infoList.value.data.status === 5)
  )
})
const canCancelAudit = computed(() => {
  return (
    proxy.$permission('assetPurchOrder:cancelAudit') &&
    infoList.value.data.status === 3 &&
    proxy.$store.state.permission.systemConfig
      .allow_asset_purch_order_approval != 0
  )
})

// const canBreak = computed(() => {
//   return (
//     proxy.$permission('assetPurchOrder:stop') &&
//     ((infoList.value.data.status === 3 &&
//       proxy.$store.state.permission.systemConfig
//         .allow_asset_purch_order_approval != 0) ||
//       infoList.value.data.status === 13 ||
//       infoList.value.data.status === 14)
//   )
// })
const showDialog = computed({
  get() {
    return props.visible
  },
  set(newValue) {
    emits('update:visible', newValue) // 更新父组件shows
  },
})

setData()
function setData() {
  let obj = {
    price: {
      label: '单价',
      value: 'price',
      type: 'column',
      formatter: proxy.$fn.TripartiteMethod,
      permission: !proxy.$permission('assetPurchOrder:price'),
      hidden: true,
    },
    orderNo: {
      label: '单号',
      value: 'orderNo',
      componentType: 'input',
      show: false,
      type: 'column',
      hidden: true,
    },
    assetApplicationNo: {
      label: '资产申论单号',
      value: 'assetApplicationNo',
      type: 'slot',
      show: false,
      hidden: true,
    },
    sumAmount: {
      label: '总金额',
      value: 'sumAmount',
      type: 'column',
      formatter: proxy.$fn.TripartiteMethod,
      permission: !proxy.$permission('assetPurchOrder:price'),
      hidden: true,
    },
    defaultSupplierPrice: {
      label: '默认供应商价格',
      value: 'defaultSupplierPrice',
      type: 'column',
      permission: !proxy.$permission('assetPurchOrder:price'),
      formatter: proxy.$fn.TripartiteMethod,
      hidden: true,
    },
  }
  tableInfo.value.fieldList = Object.values({
    ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
    ...obj,
  })
  getCustomize()
}
function returnModify() {
  if (props.orderId || props.id) {
    getCustomize()
  }
}
function showContract(id) {
  contractInfo.value.id = id
  contractInfo.value.visible = true
}
//导出excel
function exportExcel() {
  exportAssetPurchOrderDetail(filterInfo.value.query).then((resp) => {
    if (resp) {
      proxy.$fn.parseExcel(resp)
    }
  })
}
const templateArr = ref([])
const popoverVisible = ref(false)
//打印
function print() {
  selectByCodeAndDept({
    tempCode: 'assetPurchDeatil',
    deptId: infoList.value.data.deptId,
  }).then((res) => {
    if (res && res.success) {
      templateArr.value = res.data
      popoverVisible.value = true
      // 一条数据则直接打印
      if (templateArr.value.length === 1) {
        proxy.$refs.popoverShow.hidePopover()
        doPrint({
          name: templateArr.value[0].ureportName,
          params: {
            orderId: props.orderId || props.id,
            orderNo: infoList.value.data.orderNo,
          },
          callback: printCallback,
          printCount: true,
          data: {},
        })
      }
    }
  })
}
function printCallback() {
  try {
    // 打印成功增加打印次数
    updatePrintCount({
      orderNo: infoList.value.data.orderNo,
      orderId: props.orderId || props.id,
      tempCode: 'assetPurchDeatil',
      orderType: 0,
    })
  } catch (error) {}
}
function tempClick(item) {
  doPrint({
    name: item.ureportName,
    params: {
      orderId: props.orderId || props.id,
      orderNo: infoList.value.data.orderNo,
    },
    callback: printCallback,
    printCount: true,
    data: {},
  })
  popoverVisible.value = false
}
function getPirntData(temp) {
  let params = {
    tableKey:
      'assetPurchOrderDetail-com.slip.spd.entity.vo.asset.AssetPurchOrderDetailVO',
    orderIds: [props.orderId || props.id],
  }
  printAssetPurchOrderDetail(params).then((res) => {
    if (res.success && res) {
      let data = proxy.$fn.deepClone(res.data)
      let newData = data.map((item) => {
        return {
          ...item,
          ...item.orderInfo,
        }
      })
      proxy.$lodop.preview(temp, newData)
    }
  })
}
function getOrderInfo(orderId) {
  getAssetPurchOrderById(orderId).then((resp) => {
    if (resp && resp.success) {
      infoList.value['data'] = resp.data
    }
  })
}
function update() {
  modifyInfo.value.visible = true
  modifyInfo.value.title = '修改采购单'
  // 显示信息
  modifyInfo.value.orderId = props.orderId || props.id
  modifyInfo.value.tableKey =
    'assetPurchOrderDetailModify-com.slip.spd.entity.vo.purch.PurchOrderDetailVO'
}
function handelMethodRequest(method) {
  const ids = getIds(infoList.value.data)
  if (
    method === 'submit' &&
    proxy.$store.state.permission.systemConfig
      .allow_asset_purch_order_approval == 2
  ) {
    let data = {
      flowTaskCommentDto: { approvalType: 'submit' },
      processDefinitionKey: 'assetPurchOrder',
      orderIds: [infoList.value.data.id],
    }
    methodAssetPurchOrder(data, 'flowSubmit').then((resp) => {
      if (resp && resp.success) {
        getCustomize()
      }
    })
  } else if (method === 'reject') {
    proxy
      .$prompt('请输入驳回理由', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputValidator: proxy.$fn.maxString200,
        inputErrorMessage: '驳回理由不能超过200字符',
      })
      .then(({ value }) => {
        const data = {
          id: infoList.value.data.id,
          orderId: infoList.value.data.id,
          checkOpt: value,
        }
        methodAssetPurchOrder(data, method).then((resp) => {
          if (resp && resp.success) {
            getCustomize()
          }
        })
      })
  } else if (method === 'refuse') {
    proxy
      .$prompt('请输入拒绝理由', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputValidator: proxy.$fn.maxString200,
        inputErrorMessage: '拒绝理由不能超过200字符',
      })
      .then(({ value }) => {
        const data = {
          id: infoList.value.data.id,
          orderId: infoList.value.data.id,
          checkOpt: value,
        }
        methodAssetPurchOrder(data, method).then((resp) => {
          if (resp && resp.success) {
            getCustomize()
          }
        })
      })
  } else if (method === 'stop') {
    proxy
      .$prompt('请输入中止原因', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputValidator: proxy.$fn.isNotEmptyString,
        inputErrorMessage: '请输入中止原因并不超过200字符',
      })
      .then(({ value }) => {
        const data = {
          ids: ids,
          stopReason: value,
        }
        methodAssetPurchOrder(data, method).then((resp) => {
          if (resp && resp.success) {
            getCustomize()
          }
        })
      })
  } else {
    methodAssetPurchOrder(ids, method).then((resp) => {
      if (resp.success) {
        if (
          (method === 'revoke' || method === 'cancelAudit') &&
          proxy.$route.query.processInstanceId
        ) {
          proxy.$fn.setFlowPath(proxy)
          return
        }
        getCustomize()
      }
    })
  }
}
function getIds(row = undefined) {
  let ids = []
  if (row) {
    ids.push(row.id)
  } else {
    ids = tableInfo.value.selections.map((row) => row.id)
  }
  return ids
}

// 触发事件
function handleEvent(event, data) {
  switch (event) {
    case 'tableCheck':
      tableInfo.value.selections = [...data]
      break
  }
}
function getNew(id) {
  getOrderInfo(id)
  filterInfo.value.query.queryMap.orderId.value = id
  affairTableInfo.value.query.orderId = id
  getList()
}
function handleCommand(id) {
  getNew(id)
}
function showAssetApplicationDetail(row) {
  assetApplicationDetailInfo.value.id = row.assetApplicationId
  assetApplicationDetailInfo.value.visible = true
}
function getCustomize() {
  let param = {
    tableKey: tableKey.value,
  }
  getCustomizeSetting(param).then((res) => {
    if (res && res.success) {
      let data = res.data
      tableInfo.value.fieldList = proxy.$fn.setFieldList(
        tableInfo.value.fieldList,
        data.detail
      )
      filterInfo.value.query.customizeUserVO = data
      filterInfo.value.query.queryMap.orderId.value = props.orderId || props.id
      tableInfo.value.api = getAssetPurchOrdersDetailCustomizeListAll
      getOrderInfo(props.orderId || props.id)
      getList()
    }
  })
}
function returnBack() {
  emits('returnBack', false)
}
function getList() {
  getAssetPurchOrdersDetailCustomizeListAll(filterInfo.value.query).then(
    (resp) => {
      if (resp && resp.success) {
        tableInfo.value.data = resp.data
      }
    }
  )
}
</script>
<style scoped lang="scss">
:deep(.page-table) {
  .el-table {
    overflow-y: hidden;
  }
}
.model-panel-title {
  display: flex;
  align-items: center;
  .model-tips {
    display: flex;
    align-items: center;
    margin-left: 10px;
    color: #909399;
    .model-tips-nearly,
    .model-tips-expire {
      display: block;
      margin-left: 5px;
      width: 17px;
      height: 17px;
    }
    .model-tips-nearly {
      background: #fceacb;
    }
    .model-tips-expire {
      background: #f5e4e4;
    }
  }
}
:deep(.el-table) {
  .nearly-row {
    background: #fceacb;
  }
  .expire-row {
    background: #f5e4e4;
  }
}
</style>
